# -*- coding: utf-8 -*-
# **************************功能说明 *****************
import datetime
import qrcode
import requests
import csv
import re
import datetime as dt
import json
import qrcode
import base64
from io import BytesIO
import io

from lab_qrcode_uploader import generate_and_upload_qrcode  # 导入新的模块
from lab_cy_api_client import ApiClient   # 导入新的模块


# ----- kintone setting ---------
APP_DOMAIN = "payment01"
query0=''
POST_APP = {
    "APP_ID": "33",
    "API_TOKEN": "25CyFpLAMPCnTyKG3KPTps32zPU8u8zXHJgtgWfw",
    "DATE_QUERY":''
}



class AppConfig:
    """封装 Kintone 应用的配置，包括 API URL、请求头等信息。"""

    def __init__(self, domain, app_id, api_token, query=''):
        """
        初始化 AppConfig 配置对象。

        :param domain: Kintone 域名（如 'payment01'）
        :param app_id: Kintone 应用的 ID
        :param api_token: Kintone API 的认证 token
        :param query: 用于 Kintone 查询的参数（默认空字符串）
        """
        self.domain = domain
        self.app_id = app_id
        self.api_token = api_token
        self.query = query

        # 校验必需的配置是否存在
        if not self.api_token:
            raise ValueError("API Token is required")
        if not self.domain or not self.app_id:
            raise ValueError("Domain and App ID are required")

    @property
    def records_url(self):
        """
        返回 Kintone 记录 API 的完整 URL。

        :return: Kintone 记录 API 的 URL
        """
        return f'https://{self.domain}.cybozu.cn/k/v1/records.json'

    @property
    def file_upload_url(self):
        """
        返回 Kintone 文件上传 API 的完整 URL。

        :return: Kintone 文件上传 API 的 URL
        """
        return f'https://{self.domain}.cybozu.cn/k/v1/file.json'

    @property
    def record_headers(self):
        """
        返回用于访问 Kintone 记录 API 的请求头。

        :return: 请求头字典
        """
        return {
            "X-Cybozu-API-Token": self.api_token,
            'Content-Type': 'application/json'
        }

    @property
    def file_headers(self):
        """
        返回用于文件上传的请求头。

        :return: 文件上传请求头字典
        """
        return {
            "X-Cybozu-API-Token": self.api_token,
            'Content-Type': 'XMLHttpRequest'
        }

    def __str__(self):
        """
        返回 AppConfig 配置对象的简要字符串表示。

        :return: 配置的简短字符串
        """
        return f"AppConfig(domain={self.domain}, app_id={self.app_id})"

def create_record_field(field_type, value):
    """
    Helper function to create the field dictionary for Kintone records.
    """
    return {
        "type": field_type,
        "value": value
    }

def setting_RecordsJson(order_info):
    # 使用更具描述性的变量名
    kintone_config = AppConfig(APP_DOMAIN, POST_APP["APP_ID"], POST_APP["API_TOKEN"], POST_APP["DATE_QUERY"])

    try:
        # 获取订单详细信息和二维码链接
        order_data = order_info.get('order')

        qrcode_url_ali = order_info.get('qrcode_url_ali')
        qrcode_url_wx = order_info.get('qrcode_url_wx')

        # 生成二维码文件并上传
        qr_file_key_ali = generate_and_upload_qrcode(kintone_config, qrcode_url_ali)
        qr_file_key_wx = generate_and_upload_qrcode(kintone_config, qrcode_url_wx)

        # 创建设置的 JSON 数据
        setting_Json = {
            "db_no": create_record_field("Number", order_data.get('id')),
            "order_no_ali": create_record_field("SINGLE_LINE_TEXT", order_data.get('order_no_ali')),
            "amount": create_record_field("NUMBER", order_data.get('amount')),
            "description": create_record_field("MULTI_LINE_TEXT", order_data.get('description')),
            "status": create_record_field("RADIO_BUTTON", "待支付"),
            "user": create_record_field("SINGLE_LINE_TEXT", order_data.get('user')),
            "qrcode_url_ali": create_record_field("LINK", qrcode_url_ali),
            "qrcode_img_ali": create_record_field("FILE", [{"fileKey": qr_file_key_ali}]),
            "order_no_wx": create_record_field("SINGLE_LINE_TEXT", order_data.get('order_no_wx')),
            "qrcode_url_wx": create_record_field("LINK", qrcode_url_wx),
            "qrcode_img_wx": create_record_field("FILE", [{"fileKey": qr_file_key_wx}])
        }
        return setting_Json
    except requests.RequestException as e:
        print(f"Error in file upload or request: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")
def run_program():
    # 使用更具描述性的变量名
    kintone_config = AppConfig(APP_DOMAIN, POST_APP["APP_ID"], POST_APP["API_TOKEN"], POST_APP["DATE_QUERY"])

    post_json = {
        "app": POST_APP["APP_ID"],
        "records": []
    }

    response = [{"order": {
        "id": 10,
        "order_no_ali": "ALI83917511750313867",
        "order_no_wx": "ALI83917511750313867",
        "amount": "0.01",
        "description": "商品购买",
        "pay_type": "alipay",
        "status": "pending",
        "created_at": "2025-06-19T14:17:49.028002",
        "updated_at": "2025-06-19T14:17:49.028038",
        "user": "user001"
    },
        "qrcode_url_ali": "https://qr.alipay.com/bax02501kvyvxccjirm45592",
        "qrcode_url_wx": "https://qr.wx.com/bax02501kvyvxccjirm45592"
    }, {"order": {
        "id": 11,
        "order_no_ali": "ALI83917511750313868",
        "order_no_wx": "wx83917511750313868",
        "amount": "0.01",
        "description": "商品购买1",
        "pay_type": "alipay",
        "status": "pending",
        "created_at": "2025-06-19T14:17:49.028002",
        "updated_at": "2025-06-19T14:17:49.028038",
        "user": 'userWang'
    },
        "qrcode_url_ali": "https://qr.alipay.com/bax02501kvyvxccjirm45592",
        "qrcode_url_wx": "https://qr.wx.com/bax02501kvyvxccjirm45592"
    }]

    # 进一步处理多个订单
    for order_info in response:
        result1 = setting_RecordsJson(order_info)
        # print('result1',result1)
        post_json["records"].append(result1)

    # 创建 ApiClient 实例
    api_client = ApiClient(kintone_config)

    # 调用 post_records 发送数据
    res = api_client.post_records(post_json)
    print("res",res)
    if res is not None:
        try:
            print('新增成功 >>> res:', res.json())
        except AttributeError:
            print('响应不是有效的Response对象:', res)
        except ValueError:
            print('响应内容不是有效的JSON:', res.text)
    else:
        print('请求失败，返回None')

if __name__ == "__main__":
    start_time = dt.datetime.now()
    run_program()